// 观察者模式 -- 发布、订阅模式

const event = (function(){

    let clientList = {}

    const listen = function(key, fn){

        if( !key || typeof fn !== 'function' ){
            throw new Error('第一个参数 key 为必须项，第二个参数必须为一个函数')
        }

        if( !clientList[key] ) clientList[key] = []

        clientList[key].push(fn)

    }

    const trigger = function(){

        let key = Array.prototype.shift.call(arguments)

        const fns = clientList[key]

        if( !fns || fns.length === 0 ) return false

        for( let i = 0, fn; fn = fns[i++]; ){
            fn.apply(this, arguments)
        }

    }

    const remove = function(key, fn){

        const fns = clientList[key]

        if( !fns ) return false

        if( !fn ){
            fns && (fns.length = 0)
        }else{
            for( let i = fns.length - 1; i >= 0; i-- ){
                const _fn = fns[i]
                _fn === fn && (fns.splice(i, 1))
            }
        }
    }

    return {
        listen,
        trigger,
        remove
    }

})()


export default event